import Vue from "vue";
import Vuex from "vuex";
import _ from "lodash";
import users from "./users";
import { getUserInfo } from "../api/users";
import { mergeState, merge, update, updateState } from "../util/functions";

Vue.use(Vuex);

// global state
export default new Vuex.Store({
    strict: process.env.NODE_ENV !== "production",
    state: { user: null, loaded: {}, loading: {} },
    modules: {
        users
    },
    mutations: {
        merge,
        mergeState,
        update,
        updateState,
        loading: (state, payload) => merge(state, { key: "loading", data: payload }),
    },
    getters: {
        loading: ({ loading }, keys) => {
            if(_.isString(keys)) {
                return loading[keys]
            } else if(_.isObject(keys)){
                return _.reduce(_.filter(loading, keys), (result, value) => result || value, false)
            }else {
                return _.reduce(loading, (result, value) => result || value, false)
            }
        }
    },
    actions: {
        async getUserInfo({ commit }) {
            commit("loading", { user: true });
            const user = await getUserInfo();
            commit("loading", { user: false });
            commit("merge", { key: 'user', data: user });
            return user;
        }
    }
});
